package com.mmg.spzx.manager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.mmg.spzx.common.exception.MmgException;
import com.mmg.spzx.manager.listener.ExcelListener;
import com.mmg.spzx.manager.mapper.CategoryMapper;
import com.mmg.spzx.manager.service.CategoryService;
import com.mmg.spzx.model.entity.product.Category;
import com.mmg.spzx.model.vo.common.ResultCodeEnum;
import com.mmg.spzx.model.vo.product.CategoryExcelVo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> findCategoryList(Long id) {
        List<Category> categoryList = categoryMapper.findCategoryList(id);
        //根据前端element plus框架提供的列表懒加载机制，需要判断是否有子节点，如果没有子节点，需要设置为null
        if (!CollectionUtils.isEmpty(categoryList)) {
            categoryList.forEach(category -> {
                List<Category> children = categoryMapper.findCategoryList(category.getId());
                category.setHasChildren(!CollectionUtils.isEmpty(children));
            });
        }
        return categoryList;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("分类数据", "utf-8") + ".xlsx");
            //查询数据
            List<Category> categoryList = categoryMapper.findAll();
            //将Category转换为CategoryExcelVo
            List<CategoryExcelVo> categoryExcelVoList = categoryList.stream().map(category -> {
                CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
                BeanUtils.copyProperties(category, categoryExcelVo);
                return categoryExcelVo;
            }).collect(Collectors.toList());
            //导出数据
            EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class).sheet("分类数据").doWrite(categoryExcelVoList);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), CategoryExcelVo.class, new ExcelListener<CategoryExcelVo>(categoryMapper)).sheet().doRead();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
